package server.saving;

import java.io.File;
import java.util.Map;

import org.tmatesoft.sqljet.core.SqlJetException;
import org.tmatesoft.sqljet.core.SqlJetTransactionMode;
import org.tmatesoft.sqljet.core.table.ISqlJetCursor;
import org.tmatesoft.sqljet.core.table.ISqlJetTable;
import org.tmatesoft.sqljet.core.table.SqlJetDb;


public class Sqlite {
	
	private File dbfile;
	
	private SqlJetDb database = null;
	
	private ISqlJetTable table;
	
	public Sqlite(String dbPath) {
		dbfile = new File(dbPath);
	}
	
	public void open(boolean write) throws SqlJetException {
		database = SqlJetDb.open(dbfile, write);
	}
	
	public void createTable(String tableQuery, String[] indices)
			throws SqlJetException {
		try {	
			database.createTable(tableQuery);
			for (String index : indices) {
				database.createIndex(index);
			}
		} finally {
			database.commit();
		}
	}
	
	public void addToTable(Object... values)
			throws SqlJetException {
		database.beginTransaction(SqlJetTransactionMode.WRITE);
		try {
			table.insert(values);
		} finally {
			database.commit();
		}
	}
	
	private String[] getFields(ISqlJetCursor cursor) throws SqlJetException {
		String[] info = new String[cursor.getFieldsCount()];
		for (int i = 0; i < info.length; i++) info[i] = cursor.getString(i);
		return info;
	}
	
	public String[] getRowInfo(String key, String keyValue) throws SqlJetException {
		database.beginTransaction(SqlJetTransactionMode.READ_ONLY);
		try {
			return getFields(table.lookup(key, keyValue));
		} finally {
			database.commit();
		}
	}
	
	public void updateFields(String key, String keyValue,
			Map<String, Object> newValues) throws SqlJetException {
		database.beginTransaction(SqlJetTransactionMode.EXCLUSIVE);
		try {
			table.lookup(key, keyValue).updateByFieldNames(newValues);
		} finally {
			database.commit();
		}
	}
	
	public void dropTable(String tableName) throws SqlJetException {
		database.beginTransaction(SqlJetTransactionMode.WRITE);
		try {	
			database.dropTable(tableName);
		} finally {
			database.commit();
		}
	}
	
	public void dropIndices(String[] indices) throws SqlJetException {
		database.beginTransaction(SqlJetTransactionMode.WRITE);
		try {	
			for (String index : indices) {
				database.dropIndex(index);
			}
		} finally {
			database.commit();
		}
	}
	
	public void setTable(String tableName) throws SqlJetException {
		table = database.getTable(tableName);
	}
	
	public void close() throws SqlJetException {
		database.close();
	}
	
}